package com.qst.order.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ResponseTimeAggTask {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 每分钟00秒执行：聚合过去1分钟的原始数据，存入 response_time_trend 表
     */
    @Scheduled(cron = "0 * * * * ?") //  cron表达式：每分钟第0秒执行
    public void aggregateResponseTime() {
        try {
            // 1. SQL：查询过去1分钟的平均响应时间和最大响应时间
            // 注意：DATE_SUB(NOW(), INTERVAL 1 MINUTE) 确保只聚合最近1分钟的数据
            String sql = "SELECT " +
                    "DATE_FORMAT(request_time, '%Y-%m-%d %H:%i:00') AS minute_time, " +
                    "AVG(response_time) AS avg_time, " +
                    "MAX(response_time) AS max_time " +
                    "FROM api_response_time_raw " +
                    "WHERE request_time >= DATE_SUB(NOW(), INTERVAL 1 MINUTE) " +
                    "GROUP BY minute_time";

            // 2. 执行查询并将结果存入 response_time_trend 表
            jdbcTemplate.query(sql, rs -> {
                String minuteTime = rs.getString("minute_time"); // 格式：yyyy-MM-dd HH:mm:00
                long avgTime = Math.round(rs.getDouble("avg_time")); // 平均响应时间（四舍五入为整数）
                long maxTime = rs.getLong("max_time"); // 最大响应时间

                // 3. 插入或更新聚合表（避免重复数据）
                String insertSql = "INSERT INTO response_time_trend " +
                        "(timestamp, avg_response_time, max_response_time) " +
                        "VALUES (?, ?, ?) " +
                        "ON DUPLICATE KEY UPDATE " +
                        "avg_response_time = VALUES(avg_response_time), " +
                        "max_response_time = VALUES(max_response_time)";

                jdbcTemplate.update(insertSql, minuteTime, avgTime, maxTime);
                log.info("响应时间聚合成功：{}  avg={}ms  max={}ms", minuteTime, avgTime, maxTime);
            });

        } catch (Exception e) {
            log.error("响应时间聚合失败", e);
        }
    }
}